package com.zju.iotplant.config;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;


import java.util.Iterator;
import java.util.Map;

public class RestTemplateUtils {


    private static final Logger logger = LoggerFactory.getLogger(RestTemplateUtils.class);

    public static String post(Map<String, Object> map, String url) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        String jsonObj = JSONObject.toJSONString(map);
        HttpEntity<String> formEntity = new HttpEntity<>(jsonObj, headers);
        String result = getRestTemplate().postForObject(url, formEntity, String.class);
        return result;
    }

    public static String get(String url) {
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> formEntity = new HttpEntity<>(null, headers);

        ResponseEntity<String> response = getRestTemplate().exchange(url, HttpMethod.GET, formEntity, String.class);
        String resp = response.getBody();
        return resp;
    }


    private static RestTemplate getRestTemplateByTimeOut(int timeOut) {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(1000 * timeOut);
        httpRequestFactory.setConnectTimeout(1000 * timeOut);
        httpRequestFactory.setReadTimeout(1000 * timeOut);
        return new RestTemplate(httpRequestFactory);
    }

    private static RestTemplate getRestTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(1000 * 30);
        httpRequestFactory.setConnectTimeout(1000 * 30);
        httpRequestFactory.setReadTimeout(1000 * 30);
        return new RestTemplate(httpRequestFactory);
    }



}
